/*
 * Copyright (c) 2013 Hai Bison
 *
 * See the file LICENSE at the root directory of this project for copying
 * permission.
 */

package com.haibison.android.logs.providers;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;

/**
 * Providers utilities.
 * 
 * @author Hai Bison
 * @since v1.0 beta
 */
public class ProviderUtils {

    /**
     * This is singleton class.
     */
    private ProviderUtils() {
    }// ProviderUtils()

    /**
     * Gets total record count of a provider's URI.
     * 
     * @param context
     *            the context.
     * @param uri
     *            the URI to <b>content</b> (<b>not</b> <i>content item</i>) of
     *            a provider.
     * @return {@code -1} if not available, or the number of record count.
     */
    public static long getRecordCount(Context context, Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri,
                new String[] { BaseColumns._COUNT }, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst())
                    return cursor.getLong(0);
            } finally {
                cursor.close();
            }
        }

        return -1;
    }// getRecordCount()

    /**
     * Deletes the oldest record.
     * 
     * @param context
     *            the context.
     * @param uri
     *            the <i>directory</i> URI of a provider.
     * @param tableName
     *            the table name.
     * @return the number of records deleted.
     */
    public static int deleteOldestRecord(Context context, Uri uri,
            String tableName) {
        return context.getContentResolver().delete(
                uri,
                BaseCols._ID + " IN (SELECT " + BaseColumns._ID + " FROM "
                        + tableName + " ORDER BY " + BaseCols._DATE_MODIFIED
                        + " ASC LIMIT 1)", null);
    }// deleteOldestRecord()

}
